import base64
import requests
import random
import time
import datetime
import os
import io
from PIL import Image

img_li = ["fabric_img", "reference_type_img", "cloth_img", "mask_img", "mask_draw", "resize_img", "xiangao_img", "model_img", "face_img", "background_img", "origin_img", "origin_mask","logo_img", 'model_mask_img', 'reference_type_mask_img', 'pose_img']


def get_img_format(bs64_img):
    
    img_byte = base64.b64decode(bs64_img.encode())
    img_io = io.BytesIO(img_byte)
    img = Image.open(img_io)
    img_format = img.format
    # img_format = imghdr.what(img_byte, h=img_byte)
    return str(img_format).lower()


def get_time_string():
    """
    :return: 20220525140635467912
    :PS ：并发较高时尾部随机数增加
    """
    time_string = str(datetime.datetime.fromtimestamp(time.time())).replace("-", "").replace(" ", "").replace(":","").replace(".", "") + str(random.randint(100, 9999))
    return time_string


def save_byte_file(file_byte, save_path):
    with open(save_path, 'wb') as f:
        f.write(file_byte)
    return save_path


def save_bs64_img(img_str, save_path):
    image_data = base64.b64decode(img_str)
    with open(save_path, 'wb') as f:
        f.write(image_data)
    return save_path


def req_get_img_bytes(url):
    resp = requests.get(url)
    # resp = requests.get(url, verify=False)
    return resp.content


def images_to_bs64(img):
    bs64 = base64.b64encode(img)
    return bs64.decode('utf-8')


def matting_image_path_2_base64(image_path, image_path_name, save_path):

    final_path = os.path.join(save_path, image_path_name)

    if os.path.exists(final_path):
        byte_data = open(os.path.join(save_path, image_path_name), 'rb').read()
        base64_data = images_to_bs64(byte_data)
    else:
        final_name = final_path.split('/')[-1]
        final_folder = final_path[:-len(final_name)-1]
        if not os.path.exists(final_folder):
            os.makedirs(final_folder)
        byte_data = req_get_img_bytes(image_path)
        base64_data = images_to_bs64(byte_data)
        with open(final_path, 'wb') as f:
            f.write(byte_data)
    return base64_data




# message_data = req_image_to_base64(message_data)
